home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 63140 / 63140.xpi / modules / ioutils.jsm
Text File  |  2009-01-04  |  2KB  |  57 lines

  1. var EXPORTED_SYMBOLS = ['IOUtils']
  2.  
  3. IOUtils = {}
  4. IOUtils.getFile = function(path) {
  5.     if (path instanceof Components.interfaces.nsIFile) {
  6.         return path
  7.     }
  8.     if (!/^file:\/\//.test(path)) {
  9.         path = 'file://' + path
  10.     }
  11.     var ios = Components.classes["@mozilla.org/network/io-service;1"]
  12.         .getService(Components.interfaces.nsIIOService)
  13.     var fileHandler = ios.getProtocolHandler("file")
  14.         .QueryInterface(Components.interfaces.nsIFileProtocolHandler)
  15.     return fileHandler.getFileFromURLSpec(path)
  16. }
  17.  
  18. IOUtils.read = function(path) {
  19.     var file = IOUtils.getFile(path)
  20.     var data = ''
  21.     var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  22.         .createInstance(Components.interfaces.nsIFileInputStream)
  23.     var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
  24.         .createInstance(Components.interfaces.nsIScriptableInputStream)
  25.     fstream.init(file, -1, 0, 0)
  26.     sstream.init(fstream)
  27.     var str = sstream.read(4096)
  28.     while (str.length > 0) {
  29.         data += str
  30.         str = sstream.read(4096)
  31.     }
  32.     sstream.close()
  33.     fstream.close()
  34.     return data
  35. }
  36.  
  37. IOUtils.write = function(path, data, opt) {
  38.     var file = IOUtils.getFile(path)
  39.     var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream)
  40.     outStream.init(file, 0x04 | 0x08 | 0x20, 0664, 0)
  41.     var opt = opt || {}
  42.     var charset = opt.charset || "UTF-8"
  43.     var os = Components.classes["@mozilla.org/intl/converter-output-stream;1"]
  44.             .createInstance(Components.interfaces.nsIConverterOutputStream)
  45.     os.init(outStream, charset, 0, 0x0000)
  46.     os.writeString(data)
  47.     os.close()
  48. }
  49.  
  50. IOUtils.mkdir = function(path, permission) {
  51.     var file = IOUtils.getFile(path)
  52.     var per  = permission || 0744
  53.     if (!file.exists()) {
  54.         file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, per)
  55.     }
  56. }
  57.